<script setup lang="ts">
import useAppStore from '@/store/modules/app';
import HomeHeader from '@/pages/home/component/HomeHeader.vue';
import HomeRequest from '@/request/homeRequest';
import OrderRequest from '@/request/orderRequest';
import to from '@/utils/to';
import { navigate } from '@/utils/navigate';
import OrderConditionFilter from '@/pages/order/component/OrderConditionFilter.vue';
import { requestPayment } from '@/utils/requestPayment';

interface IState {
  pages: {
    pageNo: number;
    pageSize: number;
  };
  fitterParams: { orderState: string; date: string; beginDate: string; endDate: string };
  groupValue: string;
  orderList: IOrderList[];
  beeperId: number;
  beeperList: IGetCallListRes[];
  mainFlag: number;
}

const store = useAppStore();
const state = reactive<IState>({
  pages: {
    pageNo: 1,
    pageSize: 20,
  },
  fitterParams: { date: '', orderState: '', beginDate: '', endDate: '' },
  groupValue: '',
  orderList: [],
  beeperId: store.$state.beeperId || 0,
  beeperList: [],
  mainFlag: 0,
});
const { tabbarHeight } = store.$state;
const paging = ref();

onLoad(() => {
  if (!useAppStore().$state.token) return;
  fetchCallerList();
});

onShow(() => {
  state.pages.pageNo = 1;
  paging.value?.reload();
});

watch(
  () => store.$state.beeperId,
  (beeperId) => {
    state.beeperId = beeperId;
    paging.value!.reload();
  },
);

// 请求订单列表
const fetchOrderList = async (pageNo: number, pageSize: number) => {
  if (!store.$state.token) return;
  const params = { pageNo, pageSize, beeperId: state.beeperId, groupValue: state.groupValue, hasLoading: true, ...state.fitterParams };
  const [err, res] = await to(OrderRequest.GetOrderList(params));
  if (err) {
    paging.value?.complete(false);
    return;
  }
  paging.value?.complete(res.data.list);
};

// 呼叫器点击
const handleHeaderBeeperClick = async (payload: { id: number; mainFlag?: number }) => {
  state.beeperId = payload.id;
  if (payload.id !== -1 && payload.mainFlag) {
    state.mainFlag = payload.mainFlag;
  }
  paging.value.reload();
};

// 请求呼叫器列表
const fetchCallerList = async () => {
  const [err, callList] = await to(HomeRequest.GetCallerList({ type: 2, hasLoading: true }));
  if (err) return;
  state.beeperList = callList.data;
  if (!state.beeperList.some((item) => item.id === state.beeperId)) {
    state.beeperId = callList.data[0].id;
  }
};

// 继续支付
const handleContinuePayment = (data: IOrderList) => {
  OrderRequest.ScanToPayWaitOrder({ orderNos: data.orderNo, openId: store.$state.userInfo.openId, hasLoading: true }).then(async (res) => {
    const [payErr] = await to(requestPayment({ ...res.data, provider: 'wxpay', orderInfo: '' }));
    if (payErr) return;
    paging.value?.reload();
  });
};

// 再来一单
const handleRePurchase = (data: IOrderList) => {
  OrderRequest.BuyAgnGetProdInfo({ orderId: data.orderId, hasLoading: true }).then((res) => {
    const productList = res.data.goodsList.map((item) => {
      return { ...item, ...res.data, goodsList: null };
    });
    navigate({ url: `/subcontract/home/submitOrder/index?products=${encodeURIComponent(JSON.stringify(productList))}` });
  });
};
</script>

<template>
  <NotLogged v-if="!store.$state.token" />

  <template v-else>
    <view class="pos-relative h-54px z-99 flex items-center c-bg">
      <view class="flex-1">
        <van-search background="#ffc300" shape="round" use-action-slot @search="paging?.reload()" @close="paging?.reload()" @change="state.groupValue = $event.detail" :value="state.groupValue" placeholder="请输入订单编号、商品名" />
      </view>
      <view class="mx-3 flex items-center">
        <OrderConditionFilter @change="(payload) => (state.fitterParams = payload)" />
        <view @click="navigate({ url: `/subcontract/order/orderExport/index?beeperId=${state.beeperId}` })">
          <i class="i-typcn:export font-size-5"></i>
          <view class="c-text-10 text-align-center">导出</view>
        </view>
      </view>
    </view>
    <view class="pt-12px h-32px">
      <HomeHeader :is-safe-distance="true" :beeper-id="state.beeperId" :beeper-list="state.beeperList" :bg-color="'transparent'" @selected="handleHeaderBeeperClick" />
    </view>
    <view class="pt-12px" :style="{ height: `calc(100vh - ${tabbarHeight + 44 + 54 + 12}px)` }">
      <z-paging :auto-height="false" :fixed="false" ref="paging" v-model="state.orderList" @query="fetchOrderList">
        <view class="px-12px" v-for="(item, index) in state.orderList" :key="index">
          <OrderListCard @continuePay="handleContinuePayment" :is-btn="true" @goToDetail="navigate({ url: `/subcontract/order/orderDetail/index?orderId=${item.orderId}&mainFlag=${state.mainFlag}` })" @repeatPlaceOrder="handleRePurchase" :order-info="item"></OrderListCard>
        </view>
      </z-paging>
    </view>
  </template>
  <TabBar active-tab="订单" />
</template>
